
namespace Behemoth.SharePoint.WebParts {

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using aspWp = System.Web.UI.WebControls.WebParts;

    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebPartPages;

  public class WebPartUtilities {

    private static string GetToolPaneEditLink(WebControl wp) {
      WebPart spwp = wp as WebPart;
      string script;
      if (spwp != null)
        script = ToolPane.GetShowToolPaneEvent(spwp, aspWp.WebPartManager.EditDisplayMode);
      else
        script = "javascript:MSOTlPn_ShowToolPane2Wrapper('Edit', this, '" + wp.ID + "')";
      return string.Format("<a href=\"{0}\">open the tool pane</a>", script);
    }

    public static void RenderToolPaneEditLink(HtmlTextWriter writer, string descriptiveText, WebControl wp) {
      if (string.IsNullOrEmpty(descriptiveText))
        descriptiveText = "<p>Required web part properties have not been set. To configure this web part, {0}.</p>";
      writer.Write(string.Format(descriptiveText, GetToolPaneEditLink(wp)));
    }

    /// <summary> 
    /// Sets a property value of an object by reflection. 
    /// </summary> 
    /// <param name="target">Target object.</param> 
    /// <param name="name">Name of the property.</param> 
    /// <param name="value">The value to set.</param> 
    /// <returns>The property value.</returns> 
    public static void SetWebPartProperty(object target, string name, object value) {
      try {
        System.Reflection.PropertyInfo pi = target.GetType().GetProperty(name);
        pi.SetValue(target, value, null);
      } catch (Exception ex) {
        throw new Exception(string.Format("Could not set value of web part property '{0}'.", name), ex);
      }
    }

    public static object GetWebPartProperty(object target, string name) {
      try {
        System.Reflection.PropertyInfo pi = target.GetType().GetProperty(name);
        object value = pi.GetValue(target, null);
        return value;
      } catch (Exception ex) {
        throw new Exception(string.Format("Could not get value of web part property '{0}'.", name), ex);
      }
    }

    public static Type GetWebPartPropertyType(object target, string name) {
      try {
        System.Reflection.PropertyInfo pi = target.GetType().GetProperty(name);
        return pi.PropertyType;
      } catch (Exception ex) {
        throw new Exception(string.Format("Could not determine type of web part property '{0}'. Exception was: {1}", name, ex.Message), ex);
      }
    }

  } // class

} // namespace
